import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Button } from 'antd';
import styles from './Users.css';
import Factory from '../factory';
import dataEditCreate from '../addons/DataEdit'
import dataTableCreate from '../addons/DataTable'
const daoName = "COMP_CLIE_JC";
const ButtonGroup = Button.Group;
const columns = [
  { title: '客户名称', width: 300, sorter: true, dataIndex: 'KHMC', key: 'KHMC', dispaly: true, canEdit: true, filter: true },
  { title: '关联客户1', width: 300, sorter: true, dataIndex: 'GLKH1', key: 'GLKH1', dispaly: true, canEdit: true, filter: true },
  { title: '关联客户2', width: 300, sorter: true, dataIndex: 'GLKH2', key: 'GLKH2', dispaly: true, canEdit: true, filter: true },
  { title: '关联客户3', width: 300, sorter: true, dataIndex: 'GLKH3', key: 'GLKH3', dispaly: true, canEdit: true, filter: true },
  { title: '收益类型', width: 150, sorter: true, key: 'SYLX', dataIndex: 'SYLXCaption', filter: false, dispaly: true },
  { title: '第一责任人', width: 180, sorter: true, key: 'ZZRR', dataIndex: 'ZZRRCaption', filter: false, dispaly: true },
  { title: '第二责任人', width: 180, sorter: true, key: 'FZRR', dataIndex: 'FZRRCaption', filter: false, dispaly: true },
  { title: '监测起始日', width: 150, sorter: true, dataIndex: 'SJCR', key: 'SJCR', dispaly: true, canEdit: true, filter: true },
  { title: '监测截止日', width: 150, sorter: true, dataIndex: 'EJCR', key: 'EJCR', dispaly: true, canEdit: true, filter: true },
  { title: '落实标准(万/%)', width: 180, sorter: true, dataIndex: 'LSBZ', key: 'LSBZ', dispaly: true, canEdit: true, filter: true },
  { title: '备注', width: 300, sorter: true, dataIndex: 'BZ', key: 'BZ', dispaly: true, canEdit: true, filter: true },

];
let controls = [
  { name: 'KHMC', required: true, type: 'text', label: '客户名称', grid: 24 / 24 },
  { name: 'GLKH1', required: false, type: 'text', label: '关联客户1', grid: 24 / 24 },
  { name: 'GLKH2', required: false, type: 'text', label: '关联客户2', grid: 24 / 24 },
  { name: 'GLKH3', required: false, type: 'text', label: '关联客户3', grid: 24 / 24 },
  {
    name: "SYLX", label: "收益类型", required: true,
    data: [
      { value: '1', label: '存款日均' },
      { value: '2', label: '存款利润' },
      { value: '3', label: '综合收益' },
      { value: '4', label: '综合收益率' },
      { value: '5', label: '用信率' },
    ], grid: 24 / 24, type: "select"
  },

  {
    name: "ZZRR", required: true, label: "第一责任人", type: "search", grid: 24 / 24,
    fetch: {
      daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "No"
    },
    dataType: "string", placeholder: '请输入员工工号或员工名称...'
  },
  {
    name: "FZRR", label: "第二责任人", type: "search", grid: 24 / 24,
    fetch: {
      daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "No"
    },
    dataType: "string", placeholder: '请输入员工工号或员工名称...'
  },
  { name: 'SJCR', required: true, type: 'text', label: '监测起始日', grid: 24 / 24, min: 8, max: 8, placeholder: '按YYYYMMDD格式输入' },
  { name: 'EJCR', required: true, type: 'text', label: '监测截止日', grid: 24 / 24, min: 8, max: 8, placeholder: '按YYYYMMDD格式输入' },
  { name: 'LSBZ', required: true, type: 'number', dataType: "number", label: '落实标准', grid: 24 / 24, placeholder: '单位是万元/百分位' },
  { name: 'BZ', required: false, type: 'text', label: '备注', grid: 24 / 24 },

];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class SYJCLRForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false
    };
  }
  componentDidMount() {
    const permID = this.props.permID
    this.props.dispatch({
      type: `${daoName}/setKeyName`,
      payload: { keyName: "ID", permID: permID }
    });
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, page: 1, pageSize: 20 }
    });
    this.loadOptionData();
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  showModelHandler(isAdd) {
    let key = null
    if (!isAdd) {
      const len = this.props.selectedRowKeys.length;
      if (len === 0) {
        message.info('请选择要编辑的行，如果选择了多行，则使用最后一次选择！');
        return;
      }
      key = this.props.selectedRowKeys[len - 1]
    }
    this.props.dispatch({
      type: `${daoName}/openEdit`,
      payload: { key }
    });
  }

  deleteHandler() {
    const keys = this.props.selectedRowKeys;
    const len = keys.length;
    if (len === 0) {
      message.info('请选择要删除的行！');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: `你确认要删除选中的${len}行数据吗？`,
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        this.props.dispatch({
          type: `${daoName}/remove`,
          payload: { daoName, keys },
        });
      }
    });
  }
  isDate(date) {
    var I = /^(\d{4})-(\d{2})-(\d{2})$/;
    I.exec(date);
    if (!I.test(date) && RegExp.$2 <= 12 && RegExp.$3 <= 31) {
      return false;
    }
    var year, month, day;
    year = parseInt(date.split("-")[0], 10);
    month = parseInt(date.split("-")[1], 10);
    day = parseInt(date.split("-")[2], 10);
    if (!((1 <= month) && (12 >= month) && (31 >= day) && (1 <= day))) {
      return false;
    }
    if ((month <= 7) && ((month % 2) == 0) && (day >= 31)) {
      return false;
    }
    if ((month >= 8) && ((month % 2) == 1) && (day >= 31)) {
      return false;
    }
    if (month == 2) {
      if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
        if (day > 29) {
          return false;
        }
      } else {
        if (day > 28) {
          return false;
        }
      }
    }
    return true;
  }
  edidOkHandler() {
    const form = this.refs.OrganForm.getForm()
    form.validateFields((err, values) => {
      if (!err) {
        let t = `${daoName}/create`
        const { keyName, record } = this.props;
        let msg = "数据添加成功！"
        if (record[keyName]) {
          values[keyName] = record[keyName];
          t = `${daoName}/patch`
          msg = "数据修改成功！"
        }
        controls.map((c, i) => {
          if (c.type === 'cascader-select') {
            let vs = values[c.name];
            if (vs.length > 0) {
              values[c.name] = vs[vs.length - 1];
            } else {
              values[c.name] = null;
            }
          }
          if (c.dataType === "number") {
            values[c.name] = Number(values[c.name])
          } else if (c.dataType === "date" || c.dataType === "datetime") {
            values[c.name] = !values[c.name] ? null : new Date(values[c.name])
          } else {
            values[c.name] = values[c.name] === undefined ? null : values[c.name]
          }
          if (c.multiple || c.type === 'checkbox-group') {
            values[c.name] = values[c.name].join(',');
          }
        })
        let sjcr = values['SJCR'].substring(0, 4) + '-' + values['SJCR'].substring(4, 6) + '-' + values['SJCR'].substring(6, 8)
        let ejcr = values['EJCR'].substring(0, 4) + '-' + values['EJCR'].substring(4, 6) + '-' + values['EJCR'].substring(6, 8)
        let issjcr = this.isDate(sjcr)
        let isejcr = this.isDate(ejcr)
        this.state.dataChange = true;
        if (issjcr && isejcr) {
          this.props.dispatch({
            type: t,
            payload: { daoName, values },
          })
        } else {
          message.info('请正确输入监测起始日和截止日');
        }
      }
    });
  };
  hideEditHandler() {
    const form = this.refs.OrganForm.getForm();
    form.resetFields();
    if (this.state.dataChange) {
      this.props.dispatch({
        type: `${daoName}/reload`,
        payload: { daoName },
      });
      this.state.dataChange = false;
    }
    this.props.dispatch({
      type: `${daoName}/hideEdit`
    });
  };
  render() {
    let { showEdit, record, permID, pOrgID, popedomTypes } = this.props
    const pTypes = popedomTypes[permID]
    let data = <ButtonGroup style={{ zIndex: 0 }}>
      <Button onClick={this.showModelHandler.bind(this, true)}>录入</Button>
      {/* <Button onClick={this.showModelHandler.bind(this, false)}>修改</Button> */}
      <Button onClick={this.deleteHandler.bind(this)}>删除</Button>
    </ButtonGroup>
    return (
      <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
        <div>
          <div className={styles.create}>
            {data}
          </div>
          <Modal title="监测录入编辑" width={700} visible={showEdit} onOk={this.edidOkHandler.bind(this)} onCancel={this.hideEditHandler.bind(this)}
            footer={[
              <Button key="close" type="ghost" onClick={this.hideEditHandler.bind(this)}>关闭</Button>,
              <Button key="submit" type="primary" onClick={this.edidOkHandler.bind(this)}>保存</Button>
            ]}
          >
            <EditFrom ref="OrganForm" daoName={daoName} controls={controls} record={record} />
          </Modal>
          <DataTable ref="OrganTable" daoName={daoName} columns={columns} controls={controls} permID={permID} />
        </div>
      </div>
    )
  }
}
function mapStateToProps(state) {
  const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
  const { userID, orgID, pOrgID, popedomTypes } = state.menus;
  return {
    userID,
    orgID,
    pOrgID,
    popedomTypes,
    showEdit,
    selectedRowKeys,
    keyName,
    record
  }
}
SYJCLRForm = connect(mapStateToProps)(SYJCLRForm)
export default SYJCLRForm;

let render = (props) => React.createElement(SYJCLRForm, props);
let f = new Factory()
f.set("SYJCLRForm", render)
